package me.zhengjie.modules.system.domain

import com.alibaba.fastjson.annotation.JSONField
import com.fasterxml.jackson.annotation.JsonTypeName
import com.fasterxml.jackson.databind.ser.Serializers.Base
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.persistence.*
import jakarta.validation.constraints.NotNull
import me.zhengjie.common.base.BaseEntity
import me.zhengjie.common.utils.JacksonUtil
import me.zhengjie.common.utils.enums.DataScopeEnum
import org.hibernate.annotations.CreationTimestamp
import org.springframework.data.redis.core.RedisHash
import java.sql.Timestamp
import java.util.*

/**
 * 角色
 * @author Kuki Wu
 * @date 2024-11-22
 */
@Entity
@Table(name = "sys_role")
@JsonTypeName("sysrole")
@RedisHash("sysrole")
data class Role(
    @Id
    @Column(name = "role_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @get:NotNull(groups = [Menu.Update::class])
    val id: Long? = null,

    @JSONField(serialize = false)
    //@ManyToMany(mappedBy = "roles")
    @ManyToMany(mappedBy = "roles")
    @Schema(description = "用户", hidden = true)
    var users: Set<User>? = null,

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "sys_roles_menus",
        joinColumns = [JoinColumn(name = "role_id", referencedColumnName = "role_id")],
        inverseJoinColumns = [JoinColumn(name = "menu_id", referencedColumnName = "menu_id")]
    )
    @Schema(description = "菜单", hidden = true)
    var menus: Set<Menu>? = null,

    @ManyToMany
    @JoinTable(
        name = "sys_roles_depts",
        joinColumns = [JoinColumn(name = "role_id", referencedColumnName = "role_id")],
        inverseJoinColumns = [JoinColumn(name = "dept_id", referencedColumnName = "dept_id")]
    )
    @Schema(description = "部门", hidden = true)
    var depts: Set<Dept>? = null,

    @Schema(description = "名称", hidden = true)
    //@Column(name = "name")
    var name: String? = null,

    // 数据权限类型 全部 、 本级 、 自定义
    //@Column(name = "data_scope")
    @Schema(description = "数据权限，全部 、 本级 、 自定义")
    var dataScope: String = DataScopeEnum.THIS_LEVEL.value,

    // 数值越小，级别越大
    @Column(name = "level")
    @Schema(description = "级别，数值越小，级别越大")
    var level: Int = 3,

    @Schema(description = "描述") var description: String? = null
): BaseEntity(){
    annotation class Update
    companion object {
        fun fromJson(json: String):  Role? {
            val obj = JacksonUtil.parseObject(json, Role::class.java)!!
            return when (obj) {
                is Role -> obj
                else -> null
            }
        }
    }
    override fun equals(o: Any?): Boolean {
        if (this === o) return true
        if (o == null || javaClass != o.javaClass) return false
        val (id1) = o as Role
        return id == id1
    }

    override fun hashCode(): Int {
        return Objects.hash(id)
    }

}